package pers.hxy.lookweather.model.impl;

import android.util.Log;

import androidx.annotation.NonNull;

import com.google.gson.Gson;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import pers.hxy.lookweather.Config;
import pers.hxy.lookweather.bean.AqiNowBean;
import pers.hxy.lookweather.model.WeatherModel;
import pers.hxy.lookweather.presenter.WeatherListener;
import pers.hxy.lookweather.utils.JsonUtil;

public class WeatherModelImpl implements WeatherModel {
    private static final String TAG = "WeatherModelImpl";

    private final OkHttpClient okHttpClient;

    public WeatherModelImpl() {
        okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(3000, TimeUnit.MILLISECONDS)
                .build();
    }

    @Override
    public void getAqiNow(double latitude, double longitude, WeatherListener listener) {
        Log.d(TAG, "getAqiNow");
        // 格式： https://api.qweather.com/airquality/v1/current/{latitude}/{longitude}
        // latitude(必选)所需位置的纬度。十进制，最多支持小数点后两位。例如 39.92
        // longitude(必选)所需位置的经度。十进制，最多支持小数点后两位。例如 116.41
        String url = String.format("https://devapi.qweather.com/airquality/v1/current/%.2f/%.2f?key=%s",
                latitude, longitude, Config.QWEATHER_PRIVATE_KEY);
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.d(TAG, "getAqiNow onFailure " + e);
                listener.onGetAqiNow(null);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                Log.d(TAG, "getAqiNow onResponse");
                Log.d(TAG, response.headers().toString());
                String body = response.body().string();
                // Log.d(TAG, JsonUtil.getPrettyJson(body));
                AqiNowBean aqiNowBean = new Gson().fromJson(body, AqiNowBean.class);
                listener.onGetAqiNow(aqiNowBean);
                // String json = new Gson().toJson(aqiNowBean);
                // Log.d(TAG, JsonUtil.getPrettyJson(json));
            }
        });
    }
}
